package com.ebelter.scaleblesdk.ble.bluetooth.impl;

import android.bluetooth.BluetoothDevice;

import com.ebelter.scaleblesdk.ble.bluetooth.IWeightMessageCallBack;
import com.ebelter.scaleblesdk.ble.bluetooth.device.WeightDataHandle;
import com.ebelter.scaleblesdk.ble.model.AlarmClock;
import com.ebelter.scaleblesdk.ble.model.FatResult;
import com.ebelter.scaleblesdk.model.MeasureResult;
import com.ebelter.scaleblesdk.model.OfflineMeasureResult;
import com.ebelter.scaleblesdk.model.Scale;
import com.ebelter.scaleblesdk.model.ScaleUser;
import com.ebelter.scaleblesdk.ble.model.UserCommand;
import com.ebelter.scaleblesdk.model.Weight;
import com.ebelter.scaleblesdk.util.MeasureResultAnalyzer;
import com.ebelter.scaleblesdk.util.ULog;

/**
 * 体脂秤消息监听类
 * Created by pan on 2017/11/3.
 */

public class WeightMessage implements IWeightMessageCallBack {

    private static final String TAG = "WeightMessage";


    private IDeviceAlarmCallback mAlarmCallback;
    private IDeviceConnectCallback mConnectCallback;
    private IFirmwareUpgradeCallback mFirmwareUpgradeCallback;
    private IMeasureResultCallback mMeasureResultCallback;
    private IDeviceCommandCallback mCommandCallback;
    private IUserInfoChangedCallback mUserInfoChangedCallback;
    private OnWriteDataListener mListener;
    private OnDeleteAllUserListener mDeleteAllUserListener;
    private OnReceiveMeasureResultListener OnMeasureResultListener;
    private UserCommand mUserCommand;


    public void setOnReceiveMeasureResultListener(OnReceiveMeasureResultListener listener) {
        this.OnMeasureResultListener = listener;
    }

    public void setOnDeleteAllUserListener(OnDeleteAllUserListener listener) {
        this.mDeleteAllUserListener = listener;
    }

    public void setUserCommand(UserCommand command) {
        this.mUserCommand = command;
    }

    public void setUserInfoChangedCallback(IUserInfoChangedCallback callback) {
        this.mUserInfoChangedCallback = callback;
    }

    public void setDeviceAlarmCallback(IDeviceAlarmCallback alarmCallback) {
        this.mAlarmCallback = alarmCallback;
    }

    public void setDeviceConnectCallback(IDeviceConnectCallback connectCallback) {
        this.mConnectCallback = connectCallback;
    }

    public void setFirmwareUpgradeCallback(IFirmwareUpgradeCallback firmwareUpgradeCallback) {
        this.mFirmwareUpgradeCallback = firmwareUpgradeCallback;
    }

    public void setMeasureResultCallback(IMeasureResultCallback measureResultCallback) {
        this.mMeasureResultCallback = measureResultCallback;
    }

    public void setDeviceCommandCallback(IDeviceCommandCallback commandCallback) {
        this.mCommandCallback = commandCallback;
    }

    public void setOnWriteDataListener(OnWriteDataListener listener) {
        this.mListener = listener;
    }

    @Override
    public void onDisConnected() {
        ULog.i(TAG, "device disconnected.");
        if (mConnectCallback != null) {
            mConnectCallback.onDisConnected();
        }
    }

    @Override
    public void writeData(byte[] bs) {
        final byte[] sendData = bs;
        StringBuilder bytesSb = new StringBuilder();
        for (byte b : bs) {
            bytesSb.append(Integer.toHexString(b & 0xff)).append(" ");
        }
        ULog.d(TAG, "write data to device : " + bytesSb);
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (mListener != null) {
                    mListener.onWriteData(sendData);
                }

            }
        }.start();
    }

    //发现设备
    @Override
    public void onDiscovered(BluetoothDevice device) {
        ULog.i(TAG, "found device, deviceName:" + device.getName() + ", mac is :" + device.getAddress());
        if (mConnectCallback != null) {
            mConnectCallback.onDiscovered(device);
        }
    }

    @Override
    public void onDeviceConnected() {
        ULog.i(TAG, "receive device connected.");
        if (mConnectCallback != null) {
            mConnectCallback.onDeviceConnected();
        }
    }

    @Override
    public void onScaleWake() {
        ULog.i(TAG, "receive device.");
        if (mConnectCallback != null) {
            mConnectCallback.onScaleWake();
        }
    }

    @Override
    public void onScaleSleep() {
        ULog.i(TAG, "receive device sleep.");
        if (mConnectCallback != null) {
            mConnectCallback.onScaleSleep();
        }
    }

    @Override
    public void onGotAlarm(AlarmClock bean) {
        ULog.i(TAG, "获取到闹钟信息，：" + bean.toString());
        if (mAlarmCallback != null) {
            ULog.i(TAG, "-------回传闹钟------");
            mAlarmCallback.onGotAlarm(bean);
        } else {
            ULog.i(TAG, "-------btMessageCallBack------" + mAlarmCallback);
        }
    }

    @Override
    public void onGotScaleVersion(int bleVer, int scaleVer,
                                  int coefficientVer, int arithmeticVer) {
        ULog.i(TAG, "获取到秤版本信息：" +
                "ble版本：" + bleVer +
                ",秤固件版本：" + scaleVer +
                ",系数固件：" + coefficientVer +
                ",算法固件：" + arithmeticVer);
        if (mFirmwareUpgradeCallback != null) {
            mFirmwareUpgradeCallback.onGotScaleVersion(bleVer, scaleVer, coefficientVer, arithmeticVer);
        }
    }

    @Override
    public void onGotScaleClock(int year, int month, int date, int hour,
                                int minute, int second, int weekOfYear) {
        ULog.i(TAG, "获取到时钟信息：" +
                +year + "-" + month + "-" + date + " :" +
                hour + ":" + minute + ":" + second + " 周几--=" + weekOfYear);
//        if (mCommandCallback != null) {
//            mCommandCallback.onGotScaleClock(year, month, date, hour, minute, second, weekOfYear);
//        }

        if (mConnectCallback != null) {
            mConnectCallback.onGetScaleTime(year, month, date, hour, minute, second, weekOfYear);
        }
    }

    @Override
    public void onFatMeasureResult(FatResult fatResult) {
        ULog.i(TAG, "接收到脂肪测量结果：" + fatResult.toString());
        //更新秤用户信息，请求获取固件版本时，会重新发给秤
        ScaleUser user = ScaleUser.getUser();

       user.setWeight(fatResult.getWeight());

        ULog.i(TAG, "接收到脂肪测量秤返回回来的阻抗值：" + fatResult.getResistance());//zcq
        int resistance = fatResult.getResistance();
        if (resistance >= 0) {
            resistance = 255;
        }

        user.setImpedance(resistance);
       MeasureResult result = MeasureResultAnalyzer.getInstance().getMeasureResult(fatResult, ScaleUser.getUser());
        ULog.i(TAG, "实际传入进去的用户--user---" + user);//zcq


        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onReceiveMeasureResult(result);
        }
        //下发用户，更新秤的用户信息
        if (OnMeasureResultListener != null) {
            OnMeasureResultListener.onReceiveMeasureResult();
        }
    }

    @Override
    public void onWeightMeasureResult(Weight weight) {
        ULog.i(TAG, "接收到体重测量数据：" + weight.toString());
        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onWeightMeasureResult(weight);
        }
    }

    @Override
    public void onWeightOverLoad() {
        ULog.i(TAG, "重量过载");
        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onWeightOverLoad();
        }
    }

    @Override
    public void onReceiveHistoryRecord(FatResult fatResult) {
        ULog.i(TAG, "获取到历史数据：" + fatResult.toString());
        OfflineMeasureResult result = MeasureResultAnalyzer.getInstance().getOfflineMeasureResult(fatResult, ScaleUser.getUser());
        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onReceiveHistoryRecord(result);
        }
        //下发用户，更新秤的用户信息
        if (OnMeasureResultListener != null) {
            OnMeasureResultListener.onReceiveHistoryResult();
        }
    }

    @Override
    public void onUpgradeResponse(int pkgNo, boolean result) {
        ULog.i(TAG, "版本包更新返回：" + pkgNo);
        if (mFirmwareUpgradeCallback != null) {
            mFirmwareUpgradeCallback.onUpgradeResponse(pkgNo, result);
        }
    }

    @Override
    public void onUpgradeResult(int result, int type) {
        ULog.i(TAG, "更新结果：" + result);
        if (mFirmwareUpgradeCallback != null) {
            mFirmwareUpgradeCallback.onUpgradeResult(result, type);
        }
    }

    @Override
    public void onLowPower() {
        ULog.i(TAG, "设备低电");
        if (mFirmwareUpgradeCallback != null) {
            mFirmwareUpgradeCallback.onLowPower();
        }
    }

    @Override
    public void onFatMeasureError(int type) {
        ULog.i(TAG, "脂肪测量出错");
        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onFatMeasureError(type);
        }
    }

    @Override
    public void onSetClockAck() {
        ULog.i(TAG, "设置闹钟响应消息");
        if (mAlarmCallback != null) {
            mAlarmCallback.onSetClockAck();
        }
    }

    @Override
    public void onOtaUpgradeReady(boolean result) {
        ULog.i(TAG, "ota 升级已准备OK");
        if (mFirmwareUpgradeCallback != null) {
            mFirmwareUpgradeCallback.onOtaUpgradeReady(result);
        }
    }

    @Override
    public void onHistoryUploadDone() {
        ULog.i(TAG, "接收到历史完毕信号");
        if (mMeasureResultCallback != null) {
            mMeasureResultCallback.onHistoryUploadDone();
        } else {
        }
    }

    @Override
    public void onListUpdate() {
        ULog.i(TAG, "---------onListUpdate--------mUserCommand = " + mUserCommand);
        if (mUserInfoChangedCallback != null) {
            switch (mUserCommand) {
                case SEND_USER_INFO:
                    mUserInfoChangedCallback.onUserInfoUpdateSuccess();
                    break;
                case DELETE_SINGLE_USER:
//                    mUserInfoChangedCallback.onDeleteSingleUserSuccess();
                    break;
                case DELETE_ALL_USER:
                    mUserInfoChangedCallback.onDeleteAllUsersSuccess();
                    if (mDeleteAllUserListener != null) {
                        mDeleteAllUserListener.onDeleteAllUser();
                    }
                    break;
            }
        }
    }

    @Override
    public void onSDKAuthResult(byte[] bytes) {
//            sdkAuthResult = mBuilderEx.Authorize(bytes);
//            if (sdkAuthResult) {    //授权成功
//                ULog.i(TAG, "SDK auth successful.");
//                if (btMessageCallBack != null) {
//                    btMessageCallBack.onDeviceConnected();
//                }
//            } else {
//                ULog.e(TAG, "SDK auth failed. please check the sdk or ota version.");
//            }
    }

    @Override
    public void onAuthFailed() {
        ULog.i(TAG, "onAuthFailed");
        if (mCommandCallback != null) {
            mCommandCallback.onAuthFailed();
        }
    }

    @Override
    public void onAuthSuccess() {
        ULog.i(TAG, "onAuthSuccess");
        if (mCommandCallback != null) {
            mCommandCallback.onAuthSuccess();
        }
    }

    @Override
    public void onBindSuccess() {
        ULog.i(TAG, "onBindSuccess");
        if (mConnectCallback != null) {
            mConnectCallback.onBindSuccess();
        }
    }

    @Override
    public void onReceiveSha256PkgOne() {
        ULog.i(TAG, "onReceiveSha256PkgOne");
        if (mCommandCallback != null) {
            mCommandCallback.onReceiveSha256PkgOne();
        }
    }

    @Override
    public void onReceiveSha256PkgTwo() {
        ULog.i(TAG, "onReceiveSha256PkgTwo");
        if (mCommandCallback != null) {
            mCommandCallback.onReceiveSha256PkgTwo();
        }
    }

    @Override
    public void onClearBindUser() {
//        if (mCommandCallback != null) {
//            mCommandCallback.onClearBindUser();
//        }
    }

    @Override
    public void onUnitSet(WeightDataHandle.WeightUnit unit) {
        if (mCommandCallback != null) {
            mCommandCallback.onUnitSet(unit);
        }
    }

    @Override
    public void onGotLastRecordEmpty() {
        if (mCommandCallback != null) {
            mCommandCallback.onGotLastRecordEmpty();
        }
    }

    @Override
    public void onBluetoothClosed() {
        if (mCommandCallback != null) {
            mCommandCallback.onBluetoothClosed();
        }
    }

    @Override
    public void onBluetoothOpened() {
        if (mCommandCallback != null) {
            mCommandCallback.onBluetoothOpened();
        }
    }

    @Override
    public void onBleVersionGot(int bleVer) {
        Scale.getInstance().setBleVersion(bleVer);
    }


    public interface OnWriteDataListener {
        public void onWriteData(byte[] data);
    }

    public interface OnDeleteAllUserListener {
        public void onDeleteAllUser();
    }

    public interface OnReceiveMeasureResultListener {
        public void onReceiveMeasureResult();
        public void onReceiveHistoryResult();
    }


    /**
     * 释放资源的方法
     */
    public void release() {
        mAlarmCallback = null;
        mConnectCallback = null;
        mFirmwareUpgradeCallback = null;
        mMeasureResultCallback = null;
        mCommandCallback = null;
        mUserInfoChangedCallback = null;
        mListener = null;
        OnMeasureResultListener = null;
    }

}
